<template>
  <pannel-header :route="route"></pannel-header>
  <div class="btns">
    <el-button @click="open" type="primary" :icon="Plus" size="default">新增</el-button>
    <el-popconfirm
        confirm-button-text="Yes"
        cancel-button-text="No"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="是否确认删除吗？"
        @confirm="confirmEvent"
    >
      <template #reference>
        <el-button type="danger" size="default" :icon="Delete">删除</el-button>
      </template>
    </el-popconfirm>
  </div>
  <el-table :data="listData.list"
            style="width: 100%"
            @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"/>
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="name" label="姓名" width="100px"/>
    <el-table-column prop="avatar" label="头像" width="100px">
      <template #default="scope">
        <el-image :src="scope.row.avatar" style="width: 100px;height: 100px"></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="手机号"/>
    <el-table-column prop="permissionName" label="状态" width="100px">
      <template #default="scope">
        {{ scope.row.active === 1 ? '生效' : '失效' }}
      </template>
    </el-table-column>
    <el-table-column prop="age" label="年龄" width="100px"/>
    <el-table-column prop="sex" label="性别" width="100px">
      <template #default="scope">
        {{ scope.row.sex === 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间">
      <template #default="scope">
        <div class="flex-box">
          <el-icon>
            <Clock/>
          </el-icon>
          <span style="margin-left: 10px">{{ scope.row.create_time }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="open(scope.row)">
          编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="pagination-info">
    <el-pagination
        v-model:current-page="paginationData.pageNum"
        v-model:page-size="paginationData.pageSize"
        size="small"
        :page-sizes="[10, 20, 50, 100]"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--新增陪护师弹框-->
  <el-dialog v-model="dialogFormVisible"
             title="添加陪护师"
             width="500"
             :before-close="beforeClose">
    <el-form :model="form"
             ref="formRef"
             label-position="left"
             :rules="rules">
      <!--这个item是隐藏域-->
      <el-form-item prop="id" v-show="false">
        <el-input v-model="form.id"/>
      </el-form-item>
      <el-form-item label="昵称" prop="name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" placeholder="请输入昵称"/>
      </el-form-item>
      <el-form-item label="头像" prop="avatar" :label-width="formLabelWidth">
        <el-button v-if="!form.avatar" @click="openPhotoDialog">点击上传</el-button>
        <el-image v-else
                  :src="form.avatar"
                  style="width: 100px;height: 100px"/>
      </el-form-item>
      <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
        <el-select v-model="form.sex">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age" :label-width="formLabelWidth">
        <!--        @change="handleChange"-->
        <el-input-number v-model="form.age" :min="18" :max="50" placeholder="请输入年龄"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile" :label-width="formLabelWidth">
        <el-input v-model="form.mobile" autocomplete="off" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="是否生效" prop="active" :label-width="formLabelWidth">
        <el-radio-group v-model="form.active">
          <el-radio :value="0">失效</el-radio>
          <el-radio :value="1">生效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--陪护师头像列表弹框-->
  <el-dialog v-model="photodialogFormVisible" title="选择陪护师头像" width="680px">

    <div class="image-list">
      <div v-for="(item,index) in photoListData"
           :key="item.name"
           class="img-box"
           @click="selectPhotoIndex = index">
        <div v-if="selectPhotoIndex === index" class="select">
          <el-icon color="#fff">
            <Check/>
          </el-icon>
        </div>
        <el-image
            style="width: 148px;height:148px"
            :src="item.url"/>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="photodialogFormVisible = false">取消</el-button>
        <el-button type="primary"
                   @click="confirmPhoto">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {reactive, ref, onMounted, nextTick} from 'vue'
import {companion, companionList, deleteCompanion, photoList, userSetmenu} from '../../../api'
import {ElMessage} from "element-plus";
import {Check, Clock, Delete, InfoFilled, Plus} from "@element-plus/icons-vue";
import {useRoute} from 'vue-router'
import PannelHeader from "../../../components/pannel.vue";
import dayjs from "dayjs";

const route = useRoute()

//分页参数
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10
})
//列表数据
const listData = reactive({
  list: [],
  total: 0
})
const photoListData = ref([])

onMounted(() => {
  getListData()
  getPhotoListData()
})
//获取陪护师头像列表
const getPhotoListData = () => {
  photoList().then(({data}) => {
    photoListData.value = data.data
    console.log(photoListData, 'photoListData')
  })
}
//选中头像的索引值
const selectPhotoIndex = ref(0)

const getListData = () => {
  companionList(paginationData).then(({data}) => {
    console.log(data, 'companionList')
    listData.list = data.data.list
    listData.list.forEach(item => {
      item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
    })
    listData.total = data.data.total
    console.log(listData, 'listData')
  })
}

const dialogFormVisible = ref(false)
const photodialogFormVisible = ref(false)
const formRef = ref()
const formLabelWidth = '80px'
const form = reactive({
  id: '',
  mobile: '',
  active: '',
  age: 0,
  avatar: '',
  name: '',
  sex: ''
})

//弹窗关闭
const beforeClose = () => {
  dialogFormVisible.value = false
  //重置表单
  formRef.value.resetFields()
}

//打开新增的弹窗
const open = async (rowData = {}) => {
  dialogFormVisible.value = true
  //打开弹窗是异步的
  //编辑的情况下
  // 弹窗打开form是异步的
  await nextTick(() => {
    if (rowData) {
      Object.assign(form, {
        id: rowData.id,
        mobile: rowData.mobile,
        active: rowData.active,
        age: rowData.age,
        avatar: rowData.avatar,
        name: rowData.name,
        sex: rowData.sex
      })
    }
  })
}

// 名称校验
const validateName = (rule, value, callback) => {
  // 不能为空
  if (!value || value === '') {
    callback(new Error('请输入名称'))
  } else {
    callback()
  }
}

// 账号校验
const validateMobile = (rule, value, callback) => {
  // 不能为空
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value) ? callback() : callback(new Error('手机格式不对'))
  }
}

// 表单校验
const rules = reactive({
  name: [{require: true, message: '请输入昵称'}],
  avatar: [{request: true, message: '请选择头像'}],
  sex: [{request: true, message: '请选择性别'}],
  mobile: [{request: true, message: '请输入手机号'}, {validator: validateMobile, trigger: 'blur'}],
})

//提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(form, 'submitForm')
      companion(form).then(({data}) => {
        console.log(data, '创建陪护师')
        if (data.code === 10000) {
          ElMessage.success(data.message)
          dialogFormVisible.value = false
          beforeClose()
          getListData()
        } else {
          console.log(data, 'submitForm-data333')
          ElMessage.error(data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//page-size 改变时触发
const handleSizeChange = (val) => {
  paginationData.pageSize = val
  getListData()
}
//current-page 改变时触发
const handleCurrentChange = (val) => {
  paginationData.pageNum = val
  getListData()
}

//打开陪护师头像上传对话框
const openPhotoDialog = () => {
  photodialogFormVisible.value = true
}
const confirmPhoto = () => {
  form.avatar = photoListData.value[selectPhotoIndex.value].url
  photodialogFormVisible.value = false
}
//表格复选框选择事件
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => ({id: item.id}))
}

//confirmEvent 批量删除
const confirmEvent = () => {
  if (!multipleSelection.value.length) {
    return ElMessage.warning('请选择至少一条数据！')
  }
  deleteCompanion({id: multipleSelection.value}).then(({data}) => {
    console.log(multipleSelection.value, '删除陪护师')
    if (data.code === 10000) {
      ElMessage.success(data.message)
      getListData()
    } else {
      ElMessage.error(data.message)
    }
  })

}
</script>
<style lang="less" scoped>
.flex-box {
  display: flex;
  align-items: center;
}

.pagination-info {
  padding: 10px 0;
  background-color: #fff;

  .el-pagination {
    justify-content: end;
  }
}

.btns {
  padding: 10px 0 10px 10px;
  background-color: #fff;
}

.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .img-box {
    position: relative;

    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
